package com.shop.shoppingmall.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.shop.shoppingmall.dao.*;
import com.shop.shoppingmall.entity.*;
import com.shop.shoppingmall.config.AlipayConfig;
import com.shop.shoppingmall.service.ShIntegralService;
import com.shop.shoppingmall.service.ShOrderService;
import com.shop.shoppingmall.service.ShWalletService;
import com.shop.shoppingmall.util.CommonConstant;
import com.shop.shoppingmall.util.CrossOriginFilter;
import com.shop.shoppingmall.util.JwtUtil;
import com.shop.shoppingmall.util.YouBianCodeUtil;
import com.shop.shoppingmall.util.api.vo.Result;
import com.shop.shoppingmall.util.oss.XMLUtil;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 订单表(ShOrder)表控制层
 *
 * @author makejava
 * @since 2020-10-12 15:33:34
 */
@RestController
@RequestMapping("shOrder")
@Slf4j
@CrossOrigin
public class ShOrderController {

    /**
     * 服务对象
     */
    @Resource
    private ShOrderService shOrderService;
    @Resource
    private  ShUserDao shUserDao;
    @Resource
    private ShWalletDao shWalletDao;
    @Resource
    private ShBackUserDao shBackUserDao;
    @Resource
    private ShMerchantDao shMerchantDao;
    @Resource
    private  ShOrderDao shOrderDao;
    @Resource
    private  ShOrderAllDao shOrderAllDao;
    @Resource
    private  ShIntegralService shIntegralService;
    @Resource
    private  ShWalletService shWalletService;
    @Resource
    private  ShProductDao shProductDao;
    @Resource
    private ShProportionDao shProportionDao;
    @Resource
    private ShRechargeDao shRechargeDao;
    @Resource
    private ShVipController shVipController;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ShOrder selectOne(String id) {
        return this.shOrderService.queryById(id);
    }

    @PostMapping("insertOrder")
    public Result insertOrder(HttpServletRequest request, @RequestBody String jsonRequest) {
//        String name1 = JwtUtil.getUserNameByToken(request);
//        ShUser shUser = shUserDao.selectLoginName(name1);
//        if(shUser == null || name1 == null){
//            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
//        }
        JSONObject jsonObject = JSONObject.parseObject(jsonRequest);
        Map<String, Object> map = jsonObject;
        String category = map.get("categorylist").toString();
        Integer sumPrice = (Integer) map.get("sumPrice");
        Integer sums = (Integer) map.get("sums");
        List<OrderEntity> categorylist = JSONObject.parseArray(category, OrderEntity.class);
        return Result.ok("map1");

    }


    /**
     * 用户购买商品确认订单
     *
     * @param request
     * @param jsonRequest
     * @return
     */
    @PostMapping("insertOrders")
    public Result confirmOrder(HttpServletRequest request, @RequestBody String jsonRequest) {
        String name1 = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name1);
        if (shUser == null || name1 == null) {
            return Result.error(CommonConstant.SC_OK_201, "您还未注册或者登录，请先注册或登录");
        }
        ShWallet shWallet = shWalletDao.selectByUserId(shUser.getId());
        if (shWallet == null) {
            return Result.error(CommonConstant.SC_OK_202, "未查到用户钱包信息");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonRequest);
        Map<String, Object> map = jsonObject;
        String category = map.get("categorylist").toString();
        Integer sumPrice = (Integer) map.get("sumPrice");
        Integer sums = (Integer) map.get("sums");
        System.out.println(category);
        System.out.println(sumPrice);
        System.out.println(sums);
        List<OrderEntity> categorylist = JSONObject.parseArray(category, OrderEntity.class);
        return shOrderService.confirmOrder(categorylist, sumPrice, sums, shWallet);
    }

    /**
     * 根据用户id查询订单
     *
     * @param request
     * @param map
     * @return
     */
    @PostMapping("queryUserId")
    public Result queryUserId(HttpServletRequest request, @RequestBody Map map) {
        String name1 = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name1);
        if (shUser == null || name1 == null) {
            return Result.error(CommonConstant.SC_OK_201, "您还未注册或者登录，请先注册或登录");
        }
        map.put("userId", shUser.getId());
        return shOrderService.queryUserId(map);
    }


    /**
     * 查询所有订单
     *
     * @param map
     * @return
     */
    @PostMapping("/queryAll")
    public Result queryAll(@RequestBody Map map) {
        return shOrderService.queryAll(map);
    }

    /**
     * 下订单
     *
     * @param
     * @param jsonRequest
     * @return
     */
    @PostMapping("/insertOrderAll")
    public Result insertOrderAll(HttpServletRequest request, @RequestBody String jsonRequest) {
        return shOrderService.insertOrderAll(request, jsonRequest);
    }

    /**
     * 查询订单不同状态的数量
     *
     * @param request
     * @return
     */
    @GetMapping("/selectShOrderStatus")
    public Result selectShOrderStatus(HttpServletRequest request) {
        return shOrderService.selectShOrderStatus(request);
    }


    @GetMapping("/cancelOrder")
    public Result cancelOrder(String orderNumber) {
        return shOrderService.cancelOrder(orderNumber);
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        return shOrderService.selectAll();
    }


    /**
     * 店铺查询根据merchantId查询该店铺的所有订单
     * merchantId  必传
     *
     * @param request
     * @return
     */
    @PostMapping("/queryMerchant")
    public Result queryMerchant(HttpServletRequest request, @RequestBody Map map) {
        String name = JwtUtil.getUserNameByToken(request);
        ShBackUser shBackUser = shBackUserDao.selectLoginName(name);
        if (StringUtils.isBlank(name) || null == shBackUser) {
            return Result.error("请先注册或者登录！");
        }
        List<ShMerchant> shMerchantList = shMerchantDao.selectByUserId(shBackUser.getUserId());
        if (shMerchantList.size() <= 0) {
            return Result.error("您还没注册店铺,请先注册");
        }
        log.info("店铺id"+shBackUser.getUserId()+"yonhhhu dsfdsfds "+shMerchantList.get(0).getId());
        map.put("merchantId", shMerchantList.get(0).getId());
        return shOrderService.queryMerchant(map);
    }

    /**
     * 店铺处理代发货订单 修改状态保存快递单号
     *
     * @param /orderNumber 订单号
     * @param /courierNum  快递单号
     * @return
     */
    @PostMapping("/updateState")
    public Result updateState(@RequestBody Map map) {
        String orderNumber = map.get("orderNumber").toString();
        String courierNum = map.get("courierNum").toString();
        return shOrderService.updateState(orderNumber, courierNum);
    }

    @ApiOperation(value = "测试阿里支付", notes = "测试阿里支付")
    @ApiImplicitParams({})
    @PostMapping("/TestAlipay")
    public Object testAlipay(@RequestBody Map tt) {
        String orderId = (String) tt.get("orderId");
        String payid = (String) tt.get("payid");
        Map<String, Object> map = new HashMap<String, Object>();
        ShOrder shOrder = shOrderDao.queryOrderNumber(orderId);
        if (payid.equals("alipay")) {
            try {
                // 这个东西必备
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        AlipayConfig.app_id, AlipayConfig.private_key, "json", "UTF-8",
                        AlipayConfig.public_key, "RSA2");
                // 发起App支付请求
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

                if (shOrder == null) {
                    ShOrderAll shOrderAll = shOrderAllDao.selectByOrderAllNum(orderId);
                    if(shOrderAll ==null){
                        //充值会员
                        ShRecharge shRecharge = shRechargeDao.selectRechargeOrderNumber(orderId);
                        model.setOutTradeNo(shRecharge.getOrderNumber());
                        // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                        model.setTotalAmount(shRecharge.getOrderPrice().toString());
                        // 订单描述
                        model.setBody("馨T网会员充值");
                        // 订单标题
                        model.setSubject("馨T网会员充值");
                    }else{
                        //多个订单支付
                        String orderNumAll = shOrderAll.getOrderNumAll();
                        BigDecimal orderPriceAll = shOrderAll.getOrderPriceAll();
                        // 商户订单号 就是商户后台生成的订单号
                        model.setOutTradeNo(orderNumAll);
                        // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                        model.setTotalAmount(orderPriceAll.toString());
                        // 订单描述
                        model.setBody("馨T网商品购买");
                        // 订单标题
                        model.setSubject("馨T网商品购买");
                    }
                } else {
                    // 商户订单号 就是商户后台生成的订单号
                    model.setOutTradeNo(shOrder.getOrderNumber());
                    // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                    model.setTotalAmount(shOrder.getReallyPrice().toString());
                    // 订单描述
                    model.setBody("馨T网商品购买");
                    // 订单标题
                    model.setSubject("馨T网商品购买");
                }
                // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天 (屁股后面的字母一定要带，不然报错)
                model.setTimeoutExpress("30m");
                // 销售产品码 不必填
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(AlipayConfig.notify_url);
                // 通过api的方法请求阿里接口获得反馈
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                log.info(response.getBody());
                if (response.isSuccess()) {
                    log.info("调用成功");
                } else {
                    log.info("调用失败");
                }
                return response.getBody();
            } catch (Exception e) {
                return e.getMessage();
            }
        } else {
            try {
                map = shOrderService.payRequest(orderId);
                System.out.println(map);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return map;
        }
    }

    /**
     * 支付宝购买商品回调
     * @param request
     */
    @PostMapping("/AppAliPayNotify")
    public void appAliPayNotify(HttpServletRequest request) {
        log.info("----------------支付宝购买商品手机回调开始-------" + request);
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        try {
            // 调用SDK验证签名
            boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.public_key,
                    AlipayConfig.charset, "RSA2");
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            String info = "flag==" + flag + ";out_trade_no = " + out_trade_no + ";trade_no" + trade_no
                    + ";trade_status = " + trade_status + ";total_amount=" + total_amount;
            log.info("支付宝回调信息参数" + info);
            if (trade_status.equals("TRADE_SUCCESS")) {
                ShRecharge shRecharge = shRechargeDao.selectRechargeOrderNumber(out_trade_no);
                if(shRecharge !=null){
                    log.info("支付宝会员充值成功,订单号为:"+out_trade_no);
                    appAliPayNotify(out_trade_no, "");
                    shVipController.updateByUserId(shRecharge.getUserId());
                    ShUser shUser = shUserDao.selectShUserByUserId(shRecharge.getUserId());
                    shUser.setVipState("1");
                    shUserDao.update(shUser);
                }else{
                    log.info("支付宝支付订单状态修改,订单号为:" + out_trade_no);
                    appAliPayNotify(out_trade_no, "");
                    log.info("未查到订单信息,订单号为:" + out_trade_no);
                    log.info("11级分润开始,订单号为:" + out_trade_no);
                    fenrun(out_trade_no);
                }

            }
            log.info("SDK签名验证失败");
            log.info("支付宝回调处理完成++++++++++++++++++++++结束回调");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 购买商品支付后 微信回调
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/wxpayNotify")
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("微信购买商品回调 开始---------------------回调1，，，，回调1，，，，回调1");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        log.info("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), StandardCharsets.UTF_8);//获取微信调用我们notify_url的返回信息
//        System.out.println();
        Map<Object, Object> map = XMLUtil.doXMLParse(result);
        for (Object keyValue : map.keySet()) {
            System.out.println(keyValue + "=" + map.get(keyValue));
        }
        if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
            try {
                String sign = map.get("sign").toString();
                String nonce_str = map.get("nonce_str").toString();
                String out_trade_no = map.get("out_trade_no").toString();
                String total_fee = map.get("total_fee").toString();
                ShRecharge shRecharge = shRechargeDao.selectRechargeOrderNumber(out_trade_no);
                if(shRecharge != null){
                    log.info("微信会员充值成功,订单号为:"+out_trade_no);
                    appAliPayNotify(out_trade_no, "");
                    shVipController.updateByUserId(shRecharge.getUserId());
                    ShUser shUser = shUserDao.selectShUserByUserId(shRecharge.getUserId());
                    shUser.setVipState("1");
                    shUserDao.update(shUser);
                }else{
                    log.info("微信订单支付成功,订单号为:" + out_trade_no);
                    appAliPayNotify(out_trade_no,"wxpay");
                    fenrun(out_trade_no);
                }
                log.info("回调，，，，回调，，，，回调---------------------回调，，，，回调，，，，回调");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.getWriter().write(XMLUtil.setXML("SUCCESS", ""));   //告诉微信服务器，我收到信息了，不要在调用回调action了
            log.info("告诉微信服务器，我收到信息了，不要在调用回调action了");
            log.info("回调完成-------------" + XMLUtil.setXML("SUCCESS", ""));
        }
    }

    public  void appAliPayNotify(String number, String type) {
        ShOrder shOrder = shOrderDao.queryOrderNumber(number);
        if(shOrder !=null){
            if(type.equals("wxpay")){
                shOrder.setOrderStatus("2");//将订单状态改为待发货状态
                shOrder.setOrderType("2");//支付类型2微信支付 3支付宝支付
                shOrderDao.update(shOrder);
                log.info("单个订单状态修改成功,订单号为"+number+"支付类型为"+type);
            }else{
                shOrder.setOrderStatus("2");//将订单状态改为待发货状态
                shOrder.setOrderType("3");//支付类型2微信支付 3支付宝支付
                shOrderDao.update(shOrder);
                log.info("单个订单状态修改成功,订单号为"+number+"支付类型为"+type);
            }
        }else{
            ShOrderAll shOrderAll = shOrderAllDao.selectByOrderAllNum(number);
            if(shOrderAll != null){
                if(type.equals("wxpay")){
                    shOrderAll.setOrderStatus("2");//将订单状态改为待发货状态
                    shOrderAll.setOrderType("2");//支付类型2微信支付 3支付宝支付
                    shOrderAllDao.update(shOrderAll);
                    log.info("多个订单状态修改成功,订单号为"+number+"支付类型为"+type);
                    List<ShOrder> shOrders = shOrderDao.selectShOrder(shOrderAll.getId());
                    for(ShOrder shOrder1 : shOrders){
                        shOrder1.setOrderStatus("2");//将订单状态改为待发货状态
                        shOrder1.setOrderType("2");//支付类型2微信支付 3支付宝支付
                        shOrderDao.update(shOrder1);
                        log.info("多个订单的子订单状态修改成功,子订单号为"+shOrder1.getOrderNumber());
                    }
                }else{
                    shOrderAll.setOrderStatus("2");//将订单状态改为待发货状态
                    shOrderAll.setOrderType("3");//支付类型2微信支付 3支付宝支付
                    shOrderAllDao.update(shOrderAll);
                    log.info("多个订单状态修改成功,订单号为"+number+"支付类型为"+type);
                    List<ShOrder> shOrders = shOrderDao.selectShOrder(shOrderAll.getId());
                    for(ShOrder shOrder1 : shOrders){
                        shOrder1.setOrderStatus("2");//将订单状态改为待发货状态
                        shOrder1.setOrderType("3");//支付类型2微信支付 3支付宝支付
                        shOrderDao.update(shOrder1);
                        log.info("多个订单的子订单状态修改成功,子订单号为"+shOrder1.getOrderNumber());
                    }
                }
            }else{
                //充值会员
                ShRecharge shRecharge = shRechargeDao.selectRechargeOrderNumber(number);
                if(type.equals("wxpay")){
                    shRecharge.setOrderStatus("2");//将订单状态改为待发货状态
                    shRecharge.setOrderType("2");//支付类型2微信支付 3支付宝支付
                    shRechargeDao.update(shRecharge);
                    log.info("充值会员订单状态修改成功,订单号为"+number+"支付类型为"+type);
                }else{
                    log.info("正在修改");
                    shRecharge.setOrderStatus("2");//将订单状态改为待发货状态
                    shRecharge.setOrderType("3");//支付类型2微信支付 3支付宝支付
                    shRechargeDao.update(shRecharge);
                    log.info("充值会员订单状态修改成功,订单号为"+number+"支付类型为"+type);
                }
            }
        }
    }
    /**
     * 奖金分配制度
     * String userId,BigDecimal rebate
     */
    int i=0;
    public  void fenrun(String orderId) {
        i=0;
        //根据订单号查询订单信息
        List<ShProportion> shProportionList = shProportionDao.queryAll();
        ShOrder shOrders = shOrderDao.queryOrderNumber(orderId);
        //多个订单时，奖金分配
        if(shOrders == null){
            log.info("多个订单折扣分润开始<<<<<<<<<<<<<<<<<<,");
            //查出整个订单的信息，拿到用户id
            ShOrderAll shOrderAll = shOrderAllDao.selectByOrderAllNum(orderId);
            String userId = shOrderAll.getUserId();
            ShUser shUser = shUserDao.selectShUserByUserId(userId);
            //多个订单时，查出所有订单进行遍历
            List<ShOrder> shOrderAlls = shOrderDao.selectShOrder(shOrderAll.getId());
            BigDecimal rebate=new BigDecimal(0);
            for(ShOrder sh :shOrderAlls){
                //通过产品id拿到产品信息
                ShProduct shProduct = shProductDao.queryById(sh.getProductId());
                //拿到产品的折扣价格和订单中每个产品的数量进行乘法运算
                log.info("计算值为:"+new BigDecimal(shProduct.getRebatePrice()).multiply(new BigDecimal(sh.getProductNum())));
               rebate =rebate.add(new BigDecimal(shProduct.getRebatePrice()).multiply(new BigDecimal(sh.getProductNum()))) ;
            log.info("rebate值为:"+rebate);
            }
            log.info("多个订单折扣金额合计"+rebate+"==========");
            if(shUser.getVipState().equals("1")){
                //给当前用户自己分润
                log.info("给当前用户自己分润 积分为:"+rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000))+"" +
                        "用户id为"+userId);
                shIntegralService.insertInCome(rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)),userId,"","折扣积分");
                //                //修改钱包积分数量
                shWalletService.updateIntegral(userId,rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)));
            }
            //给当前用户上级分润
            ShUser sysUsersUp=shUserDao.selectCode(shUser.getSuperiorCode());//上级
            //当前用户存在上级
            if(sysUsersUp != null) {
                eachLevel(sysUsersUp, shUser, rebate, shProportionList);
            }
        }else{
            //根据查询出的订单信息，拿到用户id，商品id，商品数量
            String userId = shOrders.getUserId();
            String productId = shOrders.getProductId();
            Integer productNum = shOrders.getProductNum();

            //根据商品id查询出对应的商品信息
            ShProduct shProduct = shProductDao.queryById(productId);
            //拿到商品折扣的价格
            Double rebatePrice = shProduct.getRebatePrice();
            BigDecimal bigDecimal = new BigDecimal(rebatePrice);
            //对折扣的价格和商品数量进行乘法运算
            BigDecimal rebate = bigDecimal.multiply(new BigDecimal(productNum));
            log.info("orderId=="+orderId+"userId++"+userId+"productId--"+productId+"productNum**"+productNum+"rebate##"+rebate);
            log.info("单个订单分润>>>>>>>>>>>>>>>>>>>>>>>>>>>.");;
            ShUser shUser = shUserDao.selectShUserByUserId(userId);
            if(shUser.getVipState().equals("1")){
                //给当前用户自己分润
                log.info("给当前用户自己分润 积分为:"+rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000))+"" +
                        "用户id为"+userId);
                shIntegralService.insertInCome(rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)),userId,"","折扣积分");
                //修改钱包积分数量
                shWalletService.updateIntegral(userId,rebate.multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)));
            }
            //给当前用户上级分润
            ShUser sysUsersUp=shUserDao.selectCode(shUser.getSuperiorCode());//上级
            //当前用户存在上级
            if(sysUsersUp != null) {
                eachLevel(sysUsersUp, shUser, rebate, shProportionList);
            }
        }
    }

    /**
     * 查询用户上级,查到11级截止
     * @param sysUsers1  收益者
     * @param shUser 提供者
     * @param rebate 折扣金额
     * @param shProportionList 折扣比例集合
     */
    public  void eachLevel(ShUser sysUsers1, ShUser shUser, BigDecimal rebate,List<ShProportion> shProportionList) {
        i =i+1;
        System.out.println(i);
        if(sysUsers1.getVipState().equals("1")){
            log.info("给当前用户上级分润 积分为:"+rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000))+"" +
                    "用户id为"+sysUsers1.getId());
            shIntegralService.insertInCome(rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000)),sysUsers1.getId(),shUser.getId(),"折扣积分");
            shWalletService.updateIntegral(sysUsers1.getId(),rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000)));
        }
        ShUser sysUsersUp=shUserDao.selectCode(sysUsers1.getSuperiorCode());//上级
        if(sysUsersUp != null) {
            if(i<=10){
                eachLevel(sysUsersUp, sysUsers1, rebate, shProportionList);
            }else{
                log.info("分润结束==========================================");
                return;
            }
        } else {
            log.info("分润结束==========================================");
            return;
        }
        log.info("分润结束==========================================");
        return;
    }

    /**
     * 快递物流查询
     * @param map //number
     * @return
     */
    @PostMapping("market")
    public Result market(@RequestBody Map map) {
        String orderId = (String) map.get("number");
        return shOrderService.market(orderId);
    }
    /**
     * 修改订单信息
     * @param shOrder
     * @return
     */
    @PostMapping("updateOrder")
    public Result updateOrder( @RequestBody ShOrder shOrder) {
        return shOrderService.updateOrder(shOrder);
    }
    @PostMapping("ceshi")
    public Result ceshi(String number) {
        appAliPayNotify(number,"");
        return Result.error("dsfsfsfdsf");
    }
}
